<?php

namespace app\admin\middleware;

use app\service\jwt\JwtService;
use Closure;
use think\Request;
use Throwable;

class AdminTokenMiddleware
{

    /**
     * @param Request $request
     * @param Closure $next
     * @return $this|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            $token = trim($request->header('X-Token'));
            if (strpos($token, 'Bearer') === 0)
                $token = trim(substr($token, 6));
            if (!$token)
                return json()->data(['code' => 401, 'msg' => '请先登录', 'data' => []]);
            //检测token
            $JwtService = new JwtService();
            $getInfo = $JwtService->checkToken($token);
            if($getInfo['code']==0){
                $request->adminId = $getInfo['data']['jti'][0]->merchant_admin_id;
                $request->adminInfo = $getInfo['data']['jti'];
                $request->mer_id = $getInfo['data']['jti'][0]->mer_id;
                return $next($request);
            }
            return json()->data(['code'=>$getInfo['code'],'msg'=>$getInfo['msg'],'data'=>$getInfo['data']]);
        } catch (Throwable $e) {
            return json()->data(['code' => 428, 'msg' => '请求发生错误，请重试', 'data' => []]);
        }
    }

}